package com.ruoyi.system.kysh.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.system.kysh.entity.AcceptInf;
import com.ruoyi.system.kysh.entity.TaskPlan;
import com.ruoyi.system.kysh.entity.dto.DailyInfDto;
import com.ruoyi.system.kysh.entity.dto.DailyInfPageDto;
import com.ruoyi.system.kysh.mapper.AcceptInfMapper;
import com.ruoyi.system.kysh.service.AcceptInfService;
import com.ruoyi.system.kysh.service.TaskPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

import java.util.stream.Collectors;


@Service
public class AcceptInfServiceImpl implements AcceptInfService {

    @Autowired
    private AcceptInfMapper acceptInfMapper;

    @Autowired
    private TaskPlanService taskPlanService;


    @Override
    public boolean saveAcceptInf(AcceptInf acceptInf, Long taskId) {

        List<Long> acceptIds=acceptInfMapper.isAccept(taskId);

        if(!acceptIds.isEmpty()){
            return false;
        }

        String acceptNum = generateAcceptNum(taskId);
        acceptInf.setAcceptNum(acceptNum);
        acceptInf.setCreateTime(new Date());

        taskPlanService.changeTaskStatus(taskId,"3");
        acceptInfMapper.save(acceptInf);
        Long acceptId=acceptInfMapper.selectAcceptIdByAcceptNum(acceptNum);
        acceptInfMapper.bindAcceptAndTaskId(acceptId,taskId);

        return true;
    }

    @Override
    public void checkAndUpdateAcceptInf(AcceptInf acceptInf) {
        acceptInf.setAcceptTime(new Date());
        acceptInf.setStatus("1");
        acceptInfMapper.updateAcceptInf(acceptInf);
    }

    @Override
    public DailyInfPageDto selectByAcceptAndPages(String acceptNum, int page, int pageSize) {
        int firstIndex=(page-1)*pageSize;
        int endIndex=firstIndex+pageSize;

        List<Long> taskIds=acceptInfMapper.selectByAcceptNumAndPagesAll(acceptNum);

        if(endIndex>taskIds.size()){
            endIndex=taskIds.size();
        }

        List<Long> taskIds1 = taskIds.subList(firstIndex, endIndex);

        taskIds1=taskIds1.stream().distinct().collect(Collectors.toList());

        List<DailyInfDto> dailyInfDtos=new ArrayList<>(taskIds.size());
        taskIds1.forEach(taskId->{
            dailyInfDtos.add(taskPlanService.selectDetailInf(taskId));
        });

        DailyInfPageDto dailyInfPageDto = new DailyInfPageDto();

        dailyInfPageDto.setDailyInfDtos(dailyInfDtos);
        dailyInfPageDto.setSize(taskIds1.size());
        dailyInfPageDto.setTotal(taskIds.size());

        return dailyInfPageDto;
    }

    String generateAcceptNum(Long taskId){
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String[] strings = simpleDateFormat.format(new Date()).split("-");
        String join = String.join("", new ArrayList<>(Arrays.asList(strings)));
        String substring = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
        String taskSail=taskPlanService.selectByTaskId(taskId).getSailings();
        String taskSailing;
        if(taskSail.equals("八点班")){
            taskSailing="8";
        }else if (taskSail.equals("四点班")) {
            taskSailing="4";
        }else {
            taskSailing="0";
        }
        return substring+join+"-"+taskSailing;
    }

    @Override
    public String selectAcceptIdByAcceptNum(String acceptNum) {
        //查询到主键和验收状态
        AcceptInf acceptInf = acceptInfMapper.selectAcceptInfByAcceptNum(acceptNum);
        //查询剩下的信息，时间是task_plan的更新时间
        //taskplan中的信息
        TaskPlan taskPlan = acceptInfMapper.selectTaskPlanByAcceptNum(acceptNum);
        //查询部门名称
        TaskPlan taskPlan1 = acceptInfMapper.selectDeptName(acceptNum);
        //查询班长和验收员
        String ids  =  acceptInfMapper.selectIds(acceptNum);
        String[] idsArray = ids.split(",");
        List<Integer> idsList = new ArrayList<>();
        for(String str: idsArray){
            int value = Integer.parseInt(str.trim());//去除字符串中多余空格
            idsList.add(value);
        }
        String morName = null;
        String acceptorName = null;
        for(Integer id:idsList){
            String name =acceptInfMapper.selectMorName(id);
            if(name != null ){
                morName = name;
                break;
            }
        }
        for(Integer id:idsList){
            String name = acceptInfMapper.selectAcceptor(id);
            if(name != null ){
               acceptorName = name;
                break;
            }
        }
        //封装到一个实体类
        taskPlan.setDeptName(taskPlan1.getDeptName());
        taskPlan.setMorName(morName);
        taskPlan.setAcceptorName(acceptorName);
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonResult = null;
        try {
            jsonResult = objectMapper.writeValueAsString(Arrays.asList(acceptInf,taskPlan));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return jsonResult;
    }

    @Override
    public int bindvideoaddress(String bindVideo,Long acceptId) {
        int result = acceptInfMapper.bindvideoaddress(bindVideo,acceptId);
        return result;
    }
}
